<template>
  <div class="app-container">
    <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
      <px-form-item label="字典名称" prop="typeName">
        <px-input v-model="queryParams.typeName" maxlength="50" placeholder="请输入字典名称" clearable style="width: 240px" @keyup.enter="getList">
          <template #suffix>
            <px-icon style="cursor: pointer" @click="getList">
              <search />
            </px-icon>
          </template>
        </px-input>
      </px-form-item>
      <px-form-item label="字典类型" prop="typeCode">
        <px-input v-model="queryParams.typeCode" maxlength="50" placeholder="请输入字典类型" clearable style="width: 240px" @keyup.enter="getList">
          <template #suffix>
            <px-icon style="cursor: pointer" @click="getList">
              <search />
            </px-icon>
          </template>
        </px-input>
      </px-form-item>
      <EquipClassSelect :className="queryParams.className" :isClear="true" @changeClassName="changeClassName" @clear="clearClassName" />
      <!-- <px-form-item label="状态" prop="status">
        <px-select
          v-model="queryParams.status"
          placeholder="字典状态"
          clearable
          style="width: 240px"
        >
          <px-option
            v-for="dict in sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </px-select>
      </px-form-item>
      <px-form-item label="创建时间" style="width: 308px">
        <px-date-picker
          v-model="queryParams.dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </px-form-item> -->
      <px-form-item>
        <px-button type="primary" @click="getList">查询</px-button>
        <px-button @click="resetQuery">重置</px-button>
      </px-form-item>
    </px-form>

    <px-row :gutter="10" class="mb8">
      <px-col :span="1.5">
        <px-button v-has="'DATA_DICT_ADD'" type="primary" @click="handleAdd">新增</px-button>
      </px-col>
      <!-- <px-col :span="1.5">
        <px-button
          type="success"
          plain
          :disabled="single"
          @click="handleUpdate"
          >修改</px-button
        >
      </px-col> -->
      <px-col :span="1.5">
        <px-button v-has="'DATA_DICT_DELETE'" type="danger" plain :disabled="ids.length === 0" @click="handleDelete">删除</px-button>
      </px-col>
      <px-col :span="1.5">
        <px-button v-has="'DATA_DICT_EXPORT'" type="warning" :disabled="ids.length === 0" plain @click="handleExport">导出</px-button>
      </px-col>
    </px-row>

    <px-table
      v-loading="loading"
      :header-cell-style="{ background: '#e7eefb', color: '#000' }"
      border
      :data="typeList"
      height="calc(100vh - 350px)"
      @selection-change="handleSelectionChange"
    >
      <px-table-column type="selection" width="55" />
      <px-table-column min-width="80" label="字典编号" prop="id" show-overflow-tooltip />
      <px-table-column label="字典名称" min-width="150" prop="typeName" show-overflow-tooltip />
      <px-table-column label="字典类型" min-width="160" show-overflow-tooltip>
        <template #default="scope">
          <span class="link-type" @click="handleToItem(scope.row)">{{ scope.row.typeCode }}</span>
        </template>
      </px-table-column>
      <px-table-column label="科室" min-width="80" prop="classNameDesc" show-overflow-tooltip />
      <px-table-column label="状态" prop="status" min-width="80">
        <template #default="scope">
          <span>{{ scope.row.status === "VALID" ? "启用" : "禁用" }}</span>
        </template>
      </px-table-column>
      <px-table-column label="备注" min-width="180" prop="remark" show-overflow-tooltip />
      <px-table-column label="创建时间" prop="createTime" min-width="140" />
      <px-table-column label="操作" width="120" class-name="small-padding fixed-width" align="center">
        <template #default="scope">
          <px-tooltip content="修改" placement="top">
            <px-button
              v-has="'DATA_DICT_EDIT'"
              link
              :disabled="scope.row.status === 'INVALID'"
              type="primary"
              icon="Edit"
              @click="handleUpdate(scope.row)"
            />
          </px-tooltip>
          <px-tooltip :content="scope.row.status === 'VALID' ? '禁用' : '启用'" placement="top">
            <px-button
              v-has="'DATA_DICT_EDIT'"
              link
              :type="scope.row.status === 'VALID' ? 'warning' : 'success'"
              :icon="scope.row.status === 'VALID' ? 'CircleClose' : 'CircleCheck'"
              @click="handleEnable(scope.row)"
            />
          </px-tooltip>
          <px-tooltip content="删除" placement="top">
            <px-button v-has="'DATA_DICT_DELETE'" link type="danger" icon="Delete" @click="handleDelete(scope.row)" />
          </px-tooltip>
        </template>
      </px-table-column>
    </px-table>

    <pagination v-show="total > 0" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />

    <!-- 添加或修改参数配置对话框 -->
    <px-dialog v-model="open" :title="form.id ? '修改数据字典' : '新增数据字典'" width="800px" destroy-on-close append-to-body>
      <px-form ref="dictRef" :model="form" :rules="rules" label-width="120px">
        <px-form-item label="字典名称" prop="typeName">
          <px-input v-model="form.typeName" clearable maxlength="50" placeholder="请输入字典名称" />
        </px-form-item>
        <px-form-item label="字典类型" prop="typeCode">
          <px-input v-model="form.typeCode" maxlength="50" :disabled="form.id" clearable placeholder="请输入字典类型" />
        </px-form-item>
        <EquipClassSelect :className="form.className" @changeClassName="changeInClassName" />
        <!-- <px-form-item label="状态" prop="status">
          <px-radio-group v-model="form.status">
            <px-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</px-radio>
          </px-radio-group>
        </px-form-item> -->
        <px-form-item label="备注" prop="remark">
          <px-input v-model="form.remark" maxlength="1000" clearable type="textarea" placeholder="请输入内容" />
        </px-form-item>
      </px-form>
      <template #footer>
        <div class="dialog-footer">
          <px-button @click="cancel">取 消</px-button>
          <px-button type="primary" @click="submitForm">确 定</px-button>
        </div>
      </template>
    </px-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SYSTEM_DATA_DICT"
});
import { ableType, addType, delType, listType, updateType } from "@/api/system/dictData";
import { router } from "@/router";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, onMounted, reactive, ref, toRefs } from "vue";

const { proxy }: any = getCurrentInstance();
// const sys_normal_disable = ref([
//   {
//     value: "VALID",
//     label: "启用"
//   },
//   {
//     value: "INVALID",
//     label: "禁用"
//   }
// ]);

const open = ref(false);
const loading = ref(true);
const ids = ref([]);

const data = reactive<Record<string, any>>({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    typeName: undefined,
    typeCode: undefined
  },
  rules: {
    typeName: [{ required: true, message: "字典名称不能为空", trigger: "blur" }],
    typeCode: [{ required: true, message: "字典类型不能为空", trigger: "blur" }]
  },
  typeList: [],
  total: 0
});

const { queryParams, form, rules, total, typeList } = toRefs(data);

/** 查询字典类型列表 */
const getList = async () => {
  loading.value = true;
  const res: any = await listType(queryParams.value);
  typeList.value = res?.data;
  total.value = res?.total;
  loading.value = false;
};

const clearClassName = () => {
  queryParams.value.className = "";
};

onMounted(async () => {
  await getList();
});

// 科室组件调用父组件
const changeClassName = val => {
  queryParams.value.className = val;
};

// 科室组件调用父组件
const changeInClassName = val => {
  form.value.className = val;
};

/** 取消按钮 */
const cancel = () => {
  open.value = false;
  reset();
};
/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    typeName: undefined,
    typeCode: undefined,
    status: "VALID",
    remark: undefined
  };
};
/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  getList();
};
const handleToItem = row => {
  router.push({
    path: "/system/dataDictItem",
    query: { typeCode: row.typeCode }
  });
};
/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  open.value = true;
};

/** 多选框选中数据 */
const handleSelectionChange = selection => {
  ids.value = selection.map(item => item.id);
};
/** 修改按钮操作 */
const handleUpdate = row => {
  reset();
  form.value = JSON.parse(JSON.stringify(row));
  open.value = true;
};
/** 提交按钮 */
const submitForm = () => {
  proxy.$refs["dictRef"].validate(valid => {
    if (valid) {
      if (form.value.id) {
        updateType(form.value).then(() => {
          PxMessage.success("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addType(form.value).then(() => {
          PxMessage.success("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
};
/** 启用/禁用按钮操作 */
const handleEnable = row => {
  const delIds = row?.id ? [row.id] : ids.value;
  PxMessageBox.confirm(`是否确认${row.status === "VALID" ? "禁用" : "启用"}字典编号为${delIds.join()}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await ableType({ ids: delIds, status: row.status === "VALID" ? "INVALID" : "VALID" });
      PxMessage.success(`${row.status === "VALID" ? "禁用" : "启用"}成功`);
      getList();
    })
    .catch(() => {});
};
/** 删除按钮操作 */
const handleDelete = row => {
  const delIds = row?.id ? [row.id] : ids.value;
  PxMessageBox.confirm(`是否确认删除字典编号为${delIds.join()}的数据项？`, "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await delType({ ids: delIds });
      PxMessage.success("删除成功");
      getList();
    })
    .catch(() => {});
};
/** 导出按钮操作 */
const handleExport = () => {
  proxy.download("post", "/account/api/v1/dictType/export", proxy.addDateRange({ ids: ids.value, ...queryParams.value }));
};
</script>
